<?php
header('Content-Type: text/html; charset=utf-8');
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
require_once dirname(__FILE__) . '/../../../libs/phpMailer/class.phpmailer.php';
session_name(SESSION);
session_start();
$myPdo = DbUtils::createPdoInst();
$action = MiscUtils::getParam('action', '');
try {
  $myPdo->beginTransaction();
  switch ($action) {
    case 'save':
      save($myPdo);
      break;
    default:
      break;
  }
  $myPdo->commit();
} catch (PDOException $e) {
  echo $e->getMessage();
}

function save($myPdo) {
  if (!isset($_SESSION['index' . USER])) {
    return;
  }
  $to = MiscUtils::getParam('to', '');
  $old_pass = MiscUtils::getParam('old_pass', '');
  $new_pass = MiscUtils::getParam('new_pass', '');
  $conf_pass = MiscUtils::getParam('conf_pass', '');
  
  unset($_SESSION['old_pass']);
  unset($_SESSION['new_pass']);
  unset($_SESSION['conf_pass']);
  unset($_SESSION['old_pass_err']);
  unset($_SESSION['new_pass_err']);
  unset($_SESSION['conf_pass_err']);
  
  $is_err = 0;
  if ($_SESSION['index' . USER]->password != md5($old_pass)) {
    $_SESSION['old_pass_err'] = 'Old password is incorrect';
    $is_err = 1;
  } 
  if (strlen($new_pass) < 6 || strlen($new_pass) > 16) {
    $_SESSION['new_pass_err'] = 'Password length must be 6 - 16 chars';
    $is_err = 1;
  }
  if ($new_pass != $conf_pass) {
    $_SESSION['conf_pass_err'] = 'Confirm password is incorrect';
    $is_err = 1;
  }
  
  if ($is_err == 1) {
    $_SESSION['old_pass'] = $old_pass;
    $_SESSION['new_pass'] = $new_pass;
    $_SESSION['conf_pass'] = $conf_pass;
  } else {
    $_SESSION['index' . USER]->password = md5($new_pass);
    DbUtils::update($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer', $_SESSION['index' . USER]);
  }
  
  echo "
  <script>
  location.href = '$to';
  </script>
  ";
  return;
}
?>
